var express = require('express');
var router = express.Router();
var crypto = require('crypto');
var mysql = require('./../database');
var svgCaptcha = require('svg-captcha');

//跨域配置=========（此处特别注意，百度上都是app.all,此处要换成router.all(切记)）
router.all('*', (req, res, next) => {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Content-Type,username,Content-Length, Authorization, Accept,X-Requested-With");
  res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
  res.header("Access-Control-Allow-Credentials", "true");
  res.header("X-Powered-By", '3.2.1')
  if(req.method=="OPTIONS") res.send(200);/*让options请求快速返回*/
  else  next();
});

/* 主页 */
router.get('/', function (req, res, next) {
  let page = req.query.page || 1;
  let start = (page - 1) * 8;
  let n = 8;
  let queryCount = 'SELECT COUNT(*) AS articleNum FROM article';
  //从start开始，每次返回n个数据
  let queryArticle = 'SELECT * FROM article ORDER BY articleID DESC LIMIT ' + start + ',' + n;
  // let query = 'SELECT * FROM article ORDER BY articleID DESC';
  mysql.query(queryArticle, function (err, rows, fields) {
    let articles = rows;
    // console.log(err);
    // console.log(articles);
    //国际时间的处理
    articles.forEach(function (ele) {
      let year = ele.articleTime.getFullYear();
      let month = ele.articleTime.getMonth() + 1 > 10 ? ele.articleTime.getMonth() : '0' + (ele.articleTime.getMonth() + 1);
      let date = ele.articleTime.getDate() + 1 > 10 ? ele.articleTime.getDate() : '0' + ele.articleTime.getDate();
      ele.articleTime = year + '-' + month + '-' + date;
    });
    mysql.query(queryCount, (err, rows, fields) => {
      // console.log(rows);
      let articleNum = rows[0].articleNum;
      let pageNum = Math.ceil(articleNum / 8);
      // console.log(articles,req.session.user,pageNum,page);
      res.render('index', {
        articles: articles,
        user: req.session.user,
        pageNum: pageNum,
        page: page
      });
    });
  });
});

//登录页
router.get('/login', function (req, res, next) {
  res.render('login', { message: '', user: req.session.user });
});
router.post('/login', function (req, res, next) {
  let name = req.body.name;
  let password = req.body.password;
  let verifyCode = req.body.verifyCode;
  // console.log('user：'+ name +",密码："+password);
  //密码MD5加密
  let hash = crypto.createHash('md5');
  hash.update(password);
  password = hash.digest('hex');
  // console.log('user：'+ name +",加密后的密码："+password);
  //mysql.escape(name)防止用户提交的数据里用Sql注入攻击
  let query = 'SELECT * FROM user WHERE userName=' + mysql.escape(name) + 'AND password=' + mysql.escape(password);
  mysql.query(query, function (err, rows, fields) {
    if (err) {
      //打印的内容均在服务器的命令行窗口中，不会在浏览器中打印
      console.log(err);
      return;
    }
    let user = rows[0];
    // console.log(user);
    if (!user) {
      res.render('login', { message: '用户名或者密码错误' });
      return;
    }
    if (verifyCode != req.session.captcha) {
      res.render('login', { message: '验证码错误' });
      return;
    }
    req.session.user = user;
    res.redirect('/');
  });
});
// 生成验证码
router.get('/verify', function (req, res, next) {
  let codeConfig = {
    size: 4,// 验证码长度
    ignoreChars: '0o1i', // 验证码字符中排除 0o1i
    noise: 3, // 干扰线条的数量
    width: 110,
    height: 50
  }
  let captcha = svgCaptcha.create(codeConfig);
  req.session.captcha = captcha.text.toLowerCase();
  res.type('image/svg+xml');
  // console.log("已请求" + captcha.text);
  res.send(captcha.data);
});

//登出
router.get('/logout', (req, res, next) => {
  req.session.user = null;
  res.redirect('/');
});

//文章内容
router.get('/articles/:articleID', function (req, res, next) {
  //req.params(这个对象存储着请求时路由配置中占位符的真实内容，占位符使用“:”开头表示)
  let articleID = req.params.articleID;
  let query = "SELECT * FROM article WHERE articleID=" + mysql.escape(articleID);
  mysql.query(query, function (err, rows, fields) {
    if (err) {
      console.log(err);
      return;
    }
    let query = "UPDATE article SET articleClick = articleClick+1 WHERE articleID=" + mysql.escape(articleID);
    let article = rows[0];
    mysql.query(query, function (err, rows, fields) {
      if (err) {
        console.log(err);
        return;
      }
      let year = article.articleTime.getFullYear();
      let month = article.articleTime.getMonth() + 1 > 10 ? article.articleTime.getMonth() : '0' + (article.articleTime.getMonth() + 1);
      let date = article.articleTime.getDate() > 10 ? article.articleTime.getDate() : '0' + article.articleTime.getDate();
      article.articleTime = year + '-' + month + '-' + date;
      res.render('article', { article: article, user: req.session.user });
    });
  });
});

//发布文章页面
router.get('/edit', function (req, res, next) {
  let user = req.session.user;
  if (!user) {
    res.redirect('/login');
    return;
  }
  res.render('edit', { user: req.session.user });
});
router.post('/edit', function (req, res, next) {
  let title = req.body.title;
  let content = req.body.content;
  let author = req.session.user.userName;
  let query = 'INSERT article SET articleTitle=' + mysql.escape(title) + ', articleAuthor=' + mysql.escape(author) + ', articleContent=' + mysql.escape(content) + ',articleTime=CURDATE(),articleClick = 0';
  mysql.query(query, function (err, rows, fields) {
    if (err) {
      console.log(err);
      return;
    }
    res.redirect('/');
  });
});

//修改文章
router.get('/modify/:articleID', (req, res, next) => {
  let articleID = req.params.articleID;
  let user = req.session.user;
  let query = 'SELECT * FROM article WHERE articleID=' + mysql.escape(articleID);
  if (!user) {
    res.redirect('/login');
    return;
  }
  mysql.query(query, (err, rows, fields) => {
    if (err) {
      console.log(err);
      return;
    }
    let article = rows[0];
    let title = article.articleTitle;
    let content = article.articleContent;
    res.render('modify', {
      user: user,
      title: title,
      content: content
    });
  });
});
router.post('/modify/:articleID', (req, res, next) => {
  let articleID = req.params.articleID;
  let user = req.session.user;
  let title = req.body.title;
  let content = req.body.content;
  let query = 'UPDATE article SET articleTitle=' + mysql.escape(title) + ', articleContent=' + mysql.escape(content) + 'WHERE articleID=' + mysql.escape(articleID);
  mysql.query(query, (err, rows, fields) => {
    if (err) {
      console.log(err);
      return;
    }
    res.redirect('/');
  })
});

//删除文章
router.get('/delete/:articleID', (req, res, next) => {
  let articleID = req.params.articleID;
  let user = req.session.user;
  let query = 'DELETE FROM article WHERE articleID=' + mysql.escape(articleID);
  if (!user) {
    res.redirect('/login');
    return;
  }
  mysql.query(query, (err, rows, fields) => {
    res.redirect('/');
  })
});

//test
router.get('/test', (req, res, next) => {
  res.sendFile(process.cwd() + '/public/css/main.css');
})

router.get('/arcgis', (req, res, next) => {
  res.sendFile(process.cwd() + '/public/arcgis_js_api/library/4.10/esri/css/main.css');
})

module.exports = router;
